// ignore_for_file: non_constant_identifier_names

import 'package:flutter/material.dart';

import 'favorite_animation_icon.dart';

class FavoriteGesture extends StatefulWidget {
  final Widget child;
  static const double defaultSize = 100;
  final double size;

  const FavoriteGesture(
      {super.key, required this.child, this.size = defaultSize});

  @override
  _FavoriteGestureState createState() => _FavoriteGestureState();
}

class _FavoriteGestureState extends State<FavoriteGesture> {
  // 保存当前应该显示在屏幕上的坐标
  List<Offset> favoriteOffsets = [];

  // 第一次双击的坐标
  Offset offset = Offset.zero;
  final GlobalKey _GestureDetectorKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    var favoriteStack = Stack(
      children: favoriteOffsets
          .map((offset) => FavoriteAnimationIcon(
        key: Key(offset.toString()),
        size: widget.size,
        animationComplete: (){
          print('video - animationComplete---remove完成');
          setState(() {
            favoriteOffsets.remove(offset);
          });
          },
        position: offset,
      ))
          .toList(),
    );

    return GestureDetector(
      key: _GestureDetectorKey,
      onDoubleTapDown: (TapDownDetails details) {
        print('video-onTapDown${details.toString()}');
        offset = _globalToLocal(details.globalPosition);
      },
      onDoubleTap: _onDoubleTap,
      child: Stack(
        children: [
          widget.child,
//      当Positioned使用const修饰时，使用offset.dy或者widget.size报错Invalid const value
//      原因是使用const修饰表示Positioned是常量，即其参数需要在编译期要确定值
          favoriteStack,
        ],
      ),
    );
  }

//  Future<void> onAnimationComplete(el) async {
//    favoriteOffsets.remove(el);
//  }

  // 其实就是将相对于screen的改为相对于布局
  Offset _globalToLocal(Offset global) {
    RenderBox renderBox =
        _GestureDetectorKey.currentContext!.findRenderObject() as RenderBox;
    return renderBox.globalToLocal(global);
  }

  void _onDoubleTap() {
    // onDoubleTapDown 时记录每次点击的坐标对象，
    // 然后再onDoubleTap中添加到集合中
    setState(() {
      print('video-onDoubleTap 双击假如offset坐标${offset.dx}-${offset.dy}');
      favoriteOffsets.add(offset);
    });
  }
}
